let userDao = require('../dao/userDao');
let tokenUtil = require('../token');
let timeUtil = require('../util/timeUtil');
let cmService = require('./cmService');
let bcryptUtil = require('../util/bcryptUtil');
let apollo = require('../config/apollo');

let redis = require('../dao/redis');

let mysqlPool = require('../dao/MySQLPool');

let userService = require('../service/userService');

const redisConst = require('../const/redisConst');
const {BusiError, SysError} = require('../exception/exception');

class AgentService {
    constructor() {
    }

    async validToken (tokenStr) {
        let tokenTmp = tokenUtil.aesDecodeDef(tokenStr);
        if (!tokenTmp) return null;

        let token = JSON.parse(tokenTmp);
        if (!token) throw new BusiError(500, "agent token err:" + tokenStr);

        // todo: 24小时校验
        console.logw("agent token timestamp:", token.timestamp);

        //
        let cacheKey = redisConst.AGENT_TOKEN + ":" + token.username;
        let res = await redis.get(cacheKey);
        if (!res || res !== tokenStr) {
            console.logw("cache agent token res:" + res);
            throw new BusiError(500, "agent token err[1]:" + tokenStr);
        }

        await redis.set(cacheKey, tokenStr, 7200);
        return token.username;
    }

    /**
     *
     * @param {String} mobile
     * @param {String} password
     * @returns {Promise<null>}
     */
    async validAgentUser(mobile, password) {
        let res = await userDao.getUserByMobile(mobile);
        if (!res){
            console.logw("账号不存在:", mobile);
            throw new BusiError(500, '账号或密码错误');
        }

        let isVerify = bcryptUtil.verify(password, res.password);
        if (!isVerify) {
            console.logw("密码错误:", mobile);
            throw new BusiError(500, "账号或密码错误");
        }

        let token = JSON.stringify({
            username: res.uid,
            timestamp: new Date().getTime()
        });

        let tokenStr = tokenUtil.aesEncodeDef(token);
        let cacheKey = redisConst.AGENT_TOKEN + ":" + res.uid;
        await redis.set(cacheKey, tokenStr, 7200);

        res.token = tokenStr;
        delete res.password;

        return res;
    }

    //代理人新增加
    //获取盟主信息
    async getMasterMemberInfo(clubId) {
        let sql = 'select a.ownerUid,b.headimgurl,b.name from clubinfo a left join users b on a.ownerUid =b.uid where a.clubId = ?';
        let args = [clubId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }

    //获取玩家上级信息
    // async getPlayerMemberInfo(clubId,uid) {
    //     let sql = 'select a.agentLeader,a.coins,a.agentYield, b.headimgurl,b.name from club a left join users b on a.agentLeader =b.uid where a.clubId = ? and a.memberUid = ?';
    //     let args = [clubId,uid];
    //     let res = await mysqlPool.query(sql, args);
    //     if (res && res.length > 0){
    //         return res[0];
    //     }
    //     return null;
    // }
    //获取玩家信息
    async getPlayerMemberInfo(clubId,uid) {
        let sql = 'select a.memberUid,a.coins,a.agentYield, b.headimgurl,b.name from club a left join users b on a.memberUid =b.uid where a.clubId = ? and a.memberUid = ?';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }

    //获取我的会员信息 limit 0,1
    async getMyMemberInfo(clubId,uid,pageNo) {
       let sql = 'select a.uId,c.coins,b.headimgurl,b.name,c.agentJoinTime,c.agentUpgradeTime,c.isAgent,c.agentYield, a.gap from agent_member a left join users b on a.uId = b.uid left join club c on a.uId = c.memberUid where a.clubId = ? and a.ownerId = ? and c.clubId = ? ORDER BY a.gap ASC limit ?,20';
        let args = [clubId,uid,clubId,pageNo];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res;
        }
        return null;
    }

    //获取一个会员
    async getMyMemberInfoOne(clubId,uid,memberId) {
        let sql = 'select a.uId,c.coins,b.headimgurl,b.name,c.agentJoinTime,c.agentUpgradeTime,c.isAgent,c.agentYield, a.gap from agent_member a left join users b on a.uId = b.uid left join club c on a.uId = c.memberUid where a.clubId = ? and a.ownerId = ? and c.clubId = ? and a.uId = ?';
        let args = [clubId,uid,clubId,memberId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res;
        }
        return null;
    }

    //获取玩家抽成
    async getUserYield(clubId,uid) {
        let sql = 'select agentYield,agentLeader,agentLevel from club where clubId = ? and memberUid = ? and isAgent > 0';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }

    //修改合伙人收益
    async changeUserYield(clubId,uid,myYield) {
        let sql = 'update club set agentYield = ? where clubId = ? and memberUid = ? and isAgent > 0';
        let args = [myYield,clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

    //获取我的玩家列表
    async getMyUserList(clubId,uid) {
        let sql = 'select a.memberUid,a.isAgent,b.headimgurl,b.name from club a left join users b on a.memberUid =b.uid where a.clubId = ? and a.agentLeader = ?';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res;
        }
        return null;
    }

    //判断是否为我的直属会员
    async isMyDirectMenber(clubId,uid,memberId) {
        let sql = 'select * from club where clubId = ? and agentLeader = ? and memberUid = ? and (isAgent <= 0 or isAgent is null)';
        let args = [clubId,uid,memberId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return true;
        }
        return false;
    }

    //设置合伙人
    async setPartner(clubId,uid,memberId,myYield) {
        let sql = 'update club set isAgent = 1,agentYield = ?,agentUpgradeTime = now() where clubId = ? and memberUid = ? and agentLeader = ?';
        let args = [myYield,clubId,memberId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

    //设置合伙人表
    async setPartnerTable(clubId,memberId) {
        let sql = 'update agent_member set isAgent = 1 where clubId = ? and uId = ?';
        let args = [clubId,memberId];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

    //获取玩家分数
    async getUserCions(clubId,uid) {
        let sql = 'select coins from club where clubId = ? and memberUid = ?';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }

    //更新玩家分数
    async updateUserCions(clubId,uid,score) {
        let sql = 'update club set coins = coins + ? where clubId = ? and memberUid = ?';
        let args = [score,clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

    //玩家转账记录
    async infoUserTransfer(clubId,fromId,toId,score) {
        let sql = 'insert into agent_transfer (clubId,fromId,toId,score,createTime) values (?,?,?,?,now())';
        let args = [clubId,fromId,toId,score];
        let res = await mysqlPool.query(sql, args);
        if (res){
            return res.affectedRows;
        }
        return null;
    }

    //查询自己的转账记录
    async getMyBill(clubId,uid) {
        let sql = 'select * from agent_transfer where fromId = ? and clubId = ?';
        let args = [uid,clubId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res;
        }
        return null;
    }
    //查询自己转给某个玩家的记录
    async getMyBillToOne(clubId,uid,memberId) {
        let sql = 'select * from agent_transfer where fromId = ? and clubId = ? and toId = ?';
        let args = [uid,clubId,memberId];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res;
        }
        return null;
    }

    //判断玩家是否在代理联盟里边
    async IsInAgent(clubId,uid) {
        let sql = 'select * from club where clubId = ? and memberUid = ?';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }

    //添加会员表
    async addMember(clubId,uid,ownerId,gap,isAg) {
        let sql = 'call agent_member_door(?,?,?,?,?)';
        let args = [clubId,uid,ownerId,gap,isAg];
        await mysqlPool.query(sql, args);
    }

    //计算玩家税收和收益
    async playerScore(clubId,uid,gameType,tax,roomid) {
        if(clubId !== '5740934'){
            return;
        }
        if(!tax){
            return;
        }
        if(tax <= 0){
            return;
        }
        await userService.updateCoins(clubId, 1, uid, gameType, -tax, roomid, "");
        let sql = 'call agent_door_yield(?,?,?,?,?)';
        let args = [clubId,uid,gameType,tax,0];
        await mysqlPool.query(sql, args);
    }

    //获取上级uid
    async getLeaderUid(clubId,uid) {
        let sql = 'select agentLeader from club where clubId = ? and memberUid = ?';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if (res && res.length > 0){
            return res[0];
        }
        return null;
    }

    //获取自己直属会员的数目
    async getMyMenberNum(clubId,uid) {
        let sql = 'select count(*) from club where clubId = ? and agentLeader = ?';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0 && res[0]['count(*)'] > 0){

            return res[0]['count(*)'];
        }
        return 0;
    }
    //获取昨日今日新增会员数目 0，今天 1，昨天
    async getMyNewMenberNum(clubId,uid,isY) {
        let sql = 'select count(*) from agent_member where clubId = ? and ownerId = ? and to_days(createTime) = to_days(now())';
        if(isY > 0){
            sql = 'select count(*) from agent_member where clubId = ? and ownerId = ? and to_days(now()) - to_days( createTime) = 1';
        }
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0 && res[0]['count(*)'] > 0){

            return res[0]['count(*)'];
        }
        return 0;
    }

    //获取昨日今日税收 0，今天 1，昨天
    async getMyTaxAll(clubId,uid,isY) {
        let sql = 'select sum(tax) from agent_tax_all where clubId = ? and uId = ? and to_days(createTime) = to_days(now())';
        if(isY > 0){
            sql = 'select sum(tax) from agent_tax_all where clubId = ? and uId = ? and to_days(now()) - to_days( createTime) = 1';
        }
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0 && res[0].sum){

            return res[0].sum;
        }
        return 0;
    }

    //获取报表 0 1 2 今月 上月 上上月
    async getMyStatement(clubId,uid,isY) {
        let sql = 'select * from agent_statement where clubId = ? and uId = ? and DATE_FORMAT(createTime,\'%Y%m\') = DATE_FORMAT(CURDATE() ,\'%Y%m\')';
        if(isY == 1){
            sql = 'select * from agent_statement where clubId = ? and uId = ? and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 1';
        }
        if(isY == 2){
            sql = 'select * from agent_statement where clubId = ? and uId = ? and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 2';
        }
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            return res;
        }
        return null;
    }

    //获取当月总税收总收益
    async getMyStatementAll(clubId,uid) {
        let sql = 'select sum(tax),sum(meScore) from agent_statement where clubId = ? and uId = ? and DATE_FORMAT(createTime,\'%Y%m\') = DATE_FORMAT(CURDATE() ,\'%Y%m\')';

        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        // if(res && res.length > 0){
        //     return res;
        // }
        if(res && res.length > 0){
            return res[0];
        }
        return null;
    }

    //获取合伙人报表  0 1 2 今月 上月 上上月
    // async getMyPartnerStatement(clubId,uid,isY) {
    //     let sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and DATE_FORMAT(createTime,\'%Y%m\') = DATE_FORMAT(CURDATE() ,\'%Y%m\')';
    //     if(isY == 1){
    //         sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 1';
    //     }
    //     if(isY == 2){
    //         sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 2';
    //     }
    //     let args = [clubId,uid];
    //     let res = await mysqlPool.query(sql, args);
    //     if(res && res.length > 0){
    //         return res;
    //     }
    //     return null;
    // }

    // //获取合伙人报表  0 1 2 今月 上月 上上月
    // async getMyPartnerStatement(clubId,uid,isY) {
    //     let sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and b.isAgent > 0 and DATE_FORMAT(createTime,\'%Y%m\') = DATE_FORMAT(CURDATE() ,\'%Y%m\')';
    //     if(isY == 1){
    //         sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and b.isAgent > 0 and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 1';
    //     }
    //     if(isY == 2){
    //         sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and b.isAgent > 0 and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 2';
    //     }
    //     let args = [clubId,uid];
    //     let res = await mysqlPool.query(sql, args);
    //     if(res && res.length > 0){
    //         return res;
    //     }
    //     return null;
    // }
    //
    // //获取会员报表  0 1 2 今月 上月 上上月
    // async getMyMenberStatement(clubId,uid,isY) {
    //     let sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and b.isAgent = 0 and DATE_FORMAT(createTime,\'%Y%m\') = DATE_FORMAT(CURDATE() ,\'%Y%m\')';
    //     if(isY == 1){
    //         sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and b.isAgent = 0 and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 1';
    //     }
    //     if(isY == 2){
    //         sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and b.isAgent = 0 and PERIOD_DIFF(date_format(now(),\'%Y%m\'),date_format(createTime,\'%Y%m\')) = 2';
    //     }
    //     let args = [clubId,uid];
    //     let res = await mysqlPool.query(sql, args);
    //     if(res && res.length > 0){
    //         return res;
    //     }
    //     return null;
    // }

    //获取合伙人报表
    async getMyPartnerStatement(clubId,uid,tsDate) {
        let sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and b.isAgent > 0 and createTime = ?';
        let args = [clubId,uid,tsDate];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            return res;
        }
        return null;
    }

    //获取会员报表
    async getMyMenberStatement(clubId,uid,tsDate) {
        let sql = 'select a.*,c.name from agent_statement a left join club b on a.uId = b.memberUid left join users c on a.uId = c.uid where b.clubId = ? and b.agentLeader = ? and b.isAgent = 0 and createTime = ?';
        let args = [clubId,uid,tsDate];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            return res;
        }
        return null;
    }

    //获取自己的名片
    async getMyCard(clubId,uid) {
        let sql = 'select * from agent_user_card where clubId = ? and uId = ?';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            return res[0];
        }
        return null;
    }

    //设置自己的名片
    async setMyCard(clubId,uid,qq,wx,xl) {
        let sql = 'select * from agent_user_card where clubId = ? and uId = ?';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0){
            //更新
            let sql2 = 'update agent_user_card set qq = ?,wx = ?,xl = ? where clubId = ? and uId = ?';
            let args2 = [qq,wx,xl,clubId,uid];
            let res2 = await mysqlPool.query(sql2, args2);
            if (res2){
                return res.affectedRows;
            }
            return null;
        }else{
            //添加数据
            let sql3 = 'INSERT INTO agent_user_card (clubId,uId,qq,wx,xl) VALUES (?,?,?,?,?)';
            let args3 = [clubId,uid,qq,wx,xl];
            let res3 = await mysqlPool.query(sql3, args3);
            if (res3){
                return res.affectedRows;
            }
            return null;

        }
        return null;
    }

    // async getMyMenberNum(clubId,uid) {
    //     let sql = 'select count(*) from club where clubId = ? and agentLeader = ?';
    //     let args = [clubId,uid];
    //     let res = await mysqlPool.query(sql, args);
    //     if(res && res.length > 0 && res[0].count){
    //
    //         return res[0].count;
    //     }
    //     return 0;
    // }

    //获取直属合伙人数目
    async getMyPartnerNum(clubId,uid) {
        let sql = 'select count(*) from club where clubId = ? and agentLeader = ? and isAgent > 0';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0 && res[0]['count(*)'] > 0){

            return res[0]['count(*)'];
        }
        return 0;
    }

    //获取直属会员数目
    async getMyTrueMenberNum(clubId,uid) {
        let sql = 'select count(*) from club where clubId = ? and agentLeader = ? and (isAgent = 0 or isAgent is null)';
        let args = [clubId,uid];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0 && res[0]['count(*)'] > 0){

            return res[0]['count(*)'];
        }
        return 0;
    }

    //获取俱乐部总人数
    async getAgetnClubAllNum(clubId) {
        let sql = 'select count(*) from club where clubId = ?';
        let args = [clubId];
        let res = await mysqlPool.query(sql, args);
        if(res && res.length > 0 && res[0]['count(*)'] > 0){

            return res[0]['count(*)'];
        }
        return 0;
    }

}


let agentService = new AgentService();
module.exports = agentService;